package com.ljy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ljy.context.BaseContext;
import com.ljy.dto.LeaseOrdersDTO;
import com.ljy.dto.LeaseOrdersPageDTO;
import com.ljy.dto.OrdersPaymentDTO;
import com.ljy.dto.OrdersRefundDTO;
import com.ljy.entity.Lease;
import com.ljy.entity.LeaseOrders;
import com.ljy.entity.LeaseSpec;
import com.ljy.entity.User;
import com.ljy.exception.CreateOrdersException;
import com.ljy.exception.OrderBusinessException;
import com.ljy.mapper.LeaseMapper;
import com.ljy.mapper.LeaseOrdersMapper;
import com.ljy.mapper.LeaseSpecMapper;
import com.ljy.mapper.UserMapper;
import com.ljy.result.PageResult;
import com.ljy.service.LeaseOrdersService;
import com.ljy.utills.WeChatPayUtil;
import com.ljy.vo.*;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class LeaseOrdersServiceImpl implements LeaseOrdersService {
    @Autowired
    LeaseOrdersMapper leaseOrdersMapper;
    @Autowired
    LeaseSpecMapper leaseSpecMapper;
    @Autowired
    LeaseMapper leaseMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Override
    public LeaseOrdersSubmitVO submit(LeaseOrdersDTO dto) {
        LeaseOrders leaseOrders=new LeaseOrders();
        BeanUtils.copyProperties(dto,leaseOrders);
        //获得当前用户id
        Integer userId = BaseContext.getCurrentId();
        leaseOrders.setUserId(userId);
        //创建时间
        leaseOrders.setCreateTime(LocalDateTime.now());
        //获取到该商品的规格
        LeaseSpec spec = leaseSpecMapper.selectBySpecId(dto.getSpecId());
        //如果规格的商品id和传来的商品id不相等，抛异常
        if(!Objects.equals(spec.getLeaseId(), dto.getLeaseId())){
            throw new CreateOrdersException("规格和商品不匹配,订单创建失败");
        }
        //获得商品总价
        leaseOrders.setAmount(spec.getPrice().multiply(BigDecimal.valueOf(dto.getTimeNumber())));
        //设置规格时间
        leaseOrders.setSpecTime(spec.getTime());
        //设置状态为待支付
        leaseOrders.setStatus(LeaseOrders.PENDING_PAYMENT);
        //设置商品图片，商品名称，自提点
        Lease lease = leaseMapper.selectById(dto.getLeaseId());
        leaseOrders.setImage(lease.getImage());
        leaseOrders.setName(lease.getName());
        leaseOrders.setPickup(lease.getPickup());
        //生成订单号(当前时间戳)
        leaseOrders.setOrderNum(String.valueOf(System.currentTimeMillis()));

        leaseOrdersMapper.insert(leaseOrders);
        //传回微信支付的必要数据
        LeaseOrdersSubmitVO leaseOrdersVO=new LeaseOrdersSubmitVO();
        BeanUtils.copyProperties(leaseOrders,leaseOrdersVO);
        leaseOrdersVO.setOrderTime(LocalDateTime.now());
        return leaseOrdersVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @SneakyThrows
    @Override
    @Transactional
    public OrdersPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 当前登录用户id
        Integer userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        //如果当前无库存，就无法付款
        LeaseOrders leaseOrders = leaseOrdersMapper.getById(ordersPaymentDTO.getId());
        Lease lease = leaseMapper.selectById(leaseOrders.getLeaseId());
        if(lease.getStock()==0){
            throw  new OrderBusinessException("当前无库存，付款失败，请取消订单");
        }



        //调用微信支付接口，生成预支付交易单


        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNum(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "VR云印空间订单", //商品描述
                user.getOpenid() //微信用户的openid
        );
//        JSONObject jsonObject=new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrdersPaymentVO vo = jsonObject.toJavaObject(OrdersPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        //模拟支付回调
//        paySuccess(ordersPaymentDTO.getId());
        return vo;
    }

    @Override
    public List<LeaseOrdersVO> list() {
        Integer userId = BaseContext.getCurrentId();
        List<LeaseOrdersVO> list = leaseOrdersMapper.list(userId);
        return list;
    }

    @Override
    public LeaseOrders getOrdersById(Integer id) {
        LeaseOrders leaseOrders=leaseOrdersMapper.getById(id);
        return leaseOrders;
    }

    @Override
    public PageResult<LeaseOrders> page(LeaseOrdersPageDTO dto) {

        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        List<LeaseOrders> list=leaseOrdersMapper.selectPage(dto);
        Page<LeaseOrders> p= (Page<LeaseOrders>) list;
        return new PageResult<>(p.getTotal(),p.getResult());

    }

    @Override
    @Transactional
    public void changeStatus(Short status, Integer orderId) {
        LeaseOrders leaseOrders=new LeaseOrders();
        leaseOrders.setStatus(status);
        leaseOrders.setId(orderId);
        if(status.equals(LeaseOrders.RETURNED)){
            //如果是已归还的话，就让租赁商品库存加1
            Integer leaseId = leaseOrdersMapper.getById(orderId).getLeaseId();
            Lease lease = leaseMapper.selectById(leaseId);
            lease.setStock(lease.getStock()+1);
            leaseMapper.updateLease(lease);
        }
        else if(status.equals(LeaseOrders.USING)){
            //如果是已经自提完成了，那么就设置结束时间
            LeaseOrders order = leaseOrdersMapper.getById(orderId);
            LocalDateTime time=LocalDateTime.now().plusHours((long) order.getSpecTime() *order.getTimeNumber());
            leaseOrders.setEndTime(time);
        }
        leaseOrdersMapper.update(leaseOrders);
    }

    @Override
    public void cancelOrRefund(OrdersRefundDTO dto) {
        LeaseOrders leaseOrders=new LeaseOrders();
        leaseOrders.setId(dto.getOrderId());
        leaseOrders.setReason(dto.getReason());
        leaseOrders.setCancelTime(LocalDateTime.now());
        leaseOrders.setStatus(dto.getStatus());
        if(dto.getStatus().equals(LeaseOrders.REFUND)){
            //退款处理
        }
        leaseOrdersMapper.update(leaseOrders);
    }

    /**
     * 支付成功，修改订单状态
     *
     *
     */
    @Override
    @Transactional
    public void paySuccess(String orderNum) {
        Integer ordersId=leaseOrdersMapper.getIdByNum(orderNum);


        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        LeaseOrders orders = LeaseOrders.builder()
                .id(ordersId)
                .status(LeaseOrders.PENDING_PREPEND)
                .payTime(LocalDateTime.now())
                .build();

        leaseOrdersMapper.update(orders);
        //租赁库存减少1
        LeaseOrders leaseOrders = leaseOrdersMapper.getById(ordersId);
        Lease lease = leaseMapper.selectById(leaseOrders.getLeaseId());

        lease.setStock(lease.getStock()-1);
        //如果库存没了,就停售
        if(lease.getStock()==0){
            lease.setStatus(2);
        }
        leaseMapper.updateLease(lease);

    }

}
